package com.ym.b2b.product.service.impl;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ym.b2b.commons.exception.BaseException;
import com.ym.b2b.commons.service.BaseService;
import com.ym.b2b.product.dao.EmBProductPaperBatchDAO;
import com.ym.b2b.product.service.EmBProductPaperBatchService;
import com.ym.b2b.product.sqlbean.EmBProductPaperBatch;
import com.zc.commons.base.Result;

@Service
public class EmBProductPaperBatchServiceImpl extends BaseService implements EmBProductPaperBatchService {

    @Autowired
    private EmBProductPaperBatchDAO emBProductPaperBatchDAO;

    @Transactional
    @Override
    public Result insertEmBProductPaperBatch(EmBProductPaperBatch emBProductPaperBatch) throws BaseException {
        Result ret = new Result();
        if (CollectionUtils.isEmpty(emBProductPaperBatch.getList())) {
            ret.setCodeResult(Result.CODE_100, "请选择要插入的数据行!");
            return ret;
        }
        try {
            for (EmBProductPaperBatch e : emBProductPaperBatch.getList()) {

                String p = "[0-9a-zA-Z]{1,10}[\\+]{0,1}[^a-zA-Z]{0,15}";
                // 自定义一个批次+效期的 正则表达式举例：批次+效期.jpg 20130909+2013-09-01.jpg
                Pattern pattern = Pattern.compile(p);
                Matcher matcher = pattern.matcher(e.getFileName());
                boolean b = matcher.matches();
                if (b) {
                    try {

                        // 满足条件 自动填充 批次和效期
                        e.setValidDate(e.getFileName().split("+")[1]);
                        e.setPaperBatchno(e.getFileName().split("+")[0]);
                    } catch (Exception e1) {
                        // do not
                    }
                }

                //
                // System.out.println(e.getFileName());
                if (StringUtils.isBlank(e.getPaperBatchno())) {
                    int i = countStr(e.getFileName(), "+");
                    if (i == 1) {
                        try {
                            // 满足条件 自动填充 批次和效期
                            String strs[] = e.getFileName().split("\\+");

                            String eL0 = "[0-9]{4}[0-9]{2}[0-9]{2}";
                            Pattern p0 = Pattern.compile(eL0);
                            Matcher m0 = p0.matcher(strs[0]);
                            boolean dateFlag0 = m0.matches();
                            if (dateFlag0) {
                                e.setPaperBatchno(strs[0]);
                            }
                            String eL1 = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";
                            Pattern p1 = Pattern.compile(eL1);
                            Matcher m1 = p1.matcher(strs[1]);
                            boolean dateFlag1 = m1.matches();
                            if (dateFlag1) {
                                e.setValidDate(strs[1]);
                            }
                        } catch (Exception e1) {
                            // do not
                        }
                    }
                }

                // 判断重复
                EmBProductPaperBatch sv = new EmBProductPaperBatch();
                sv.setUploadId(e.getUploadId());
                sv.setProductCode(e.getProductCode());
                List<EmBProductPaperBatch> l = emBProductPaperBatchDAO.searchEmBProductPaperBatch(sv);
                if (CollectionUtils.isNotEmpty(l)) {
                    continue;
                }
                emBProductPaperBatchDAO.insertEmBProductPaperBatch(e);
            }
            return ret;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("新增资质信息失败!");
        }

    }

    /**
     * 判断str1中包含str2的个数
     * 
     * @param str1
     * @param str2
     * @return counter
     */
    public static int countStr(String str1, String str2) {
        int counter = 0;
        if (str1.indexOf(str2) == -1) {
            return 0;
        } else if (str1.indexOf(str2) != -1) {
            counter++;
            countStr(str1.substring(str1.indexOf(str2) + str2.length()), str2);
            return counter;
        }
        return 0;
    }

    @Transactional
    @Override
    public Result deleteEmBProductPaperBatch(EmBProductPaperBatch emBProductPaperBatch) throws BaseException {
        Result ret = new Result();
        if (CollectionUtils.isEmpty(emBProductPaperBatch.getList())) {
            ret.setCodeResult(Result.CODE_100, "请选择要删除的数据行!");
            return ret;
        }
        try {
            for (EmBProductPaperBatch e : emBProductPaperBatch.getList()) {
                emBProductPaperBatchDAO.deleteEmBProductPaperBatch(e);
            }
            return ret;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("删除失败!");
        }
    }

    @Transactional
    @Override
    public Result updateEmBProductPaperBatch(EmBProductPaperBatch emBProductPaperBatch) throws BaseException {
        Result result = this.checkInputEmBProductPaperBatch(emBProductPaperBatch);
        if (!result.getCode().equals("200")) return result;
        try {
            emBProductPaperBatchDAO.updateEmBProductPaperBatch(emBProductPaperBatch);
            result.setResult("更新资质文件成功!");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException(Result.CODE_100, "更新资质文件失败!");
        }
        return result;
    }

    private Result checkInputEmBProductPaperBatch(EmBProductPaperBatch p) {
        Result result = new Result();
        if (p.getPaperBatchId() == null) {
            result.setCodeResult(Result.CODE_100, "缺少ID!");
            return result;
        }
        p.setUpdateDate(new Date());
        return result;

    }

}
